package utils

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
	"github.com/gorilla/websocket"
	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"

	"net/http"
	"time"
)

import _ "github.com/jinzhu/gorm/dialects/mysql" //千万别忘这句

var (
	DB  *gorm.DB
	Red *redis.Client
)

// InitConfig 加载配置文件
func InitConfig() {
	viper.SetConfigName("app")             //配置文件名
	viper.AddConfigPath("ginchat\\config") //配置文件路径

	err := viper.ReadInConfig() //进行读取
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("config app:", viper.Get("app"))
	fmt.Println("config mysql:", viper.Get("mysql"))

}
func InitMySQL() {

	//自定义日志模板 打印sql语句
	//newLogger := logger.New(
	//	log.New(os.Stdout, "\r\n", log.LstdFlags),
	//	logger.Config{
	//		SlowThreshold: time.Second, //慢SQL阈值
	//		LogLevel:      logger.Info, //级别
	//		Colorful:      true,        //彩色
	//	})

	DB, _ = gorm.Open("mysql", viper.GetString("mysql.dns"))
	//user := models.UserBasic{}
	//DB.Find(&user)
	//fmt.Println(user)

	//开启日志打印
	DB.LogMode(true)
}

func InitRedis() {
	//全局的
	Red = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // 密码
		DB:       0,  // 数据库，从0开始
		PoolSize: 30, // 连接池大小
	})
}

const (
	PublishKey = "websocket"
)

// Publish 发布消息到Redis
func Publish(ctx context.Context, channel string, msg string) error {
	var err error
	err = Red.Publish(ctx, channel, msg).Err()
	if err != nil {
		fmt.Println(err)
	}
	return err
}

// Subscribe 订阅Redis消息
func Subscribe(ctx context.Context, channel string) (string, error) {
	sub := Red.Subscribe(ctx, channel)
	msg, err := sub.ReceiveMessage(ctx)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Subscribe......", msg.Payload)
	return msg.Payload, err
}

// 防止跨域站点伪造请求
var upGrade = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func SendMsg(c *gin.Context) {
	ws, err := upGrade.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		fmt.Println(err)
		return
	}

	defer func(ws *websocket.Conn) {
		err = ws.Close()
		if err != nil {
			fmt.Println(err)
			return
		}
	}(ws)

	MsgHandler(ws, c)
}

func MsgHandler(ws *websocket.Conn, c *gin.Context) {
	msg, err := Subscribe(c, PublishKey)
	if err != nil {
		fmt.Println(err)
	}
	tm := time.Now().Format("2006-01-02 15:04:05")
	m := fmt.Sprintf("[ws][%s]:%s", tm, msg)
	err = ws.WriteMessage(1, []byte(m))
}
